package com.ulook.lookplanet.ui.home.modify;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageUtil;
import com.donkingliang.imageselector.utils.UriUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.common.ActivityCode;
import com.ulook.lookplanet.util.StringUtil;
import com.ulook.lookplanet.util.ThrowException;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ModifyUserActivity extends AppCompatActivity {

    private ModifyUserViewModel viewModel;
    private QMUIRadiusImageView2 head;
    private TextView name;
    private TextView age;
    private RadioGroup gender;
    private TextView star;
    private TextView city;
    private TextView hobby;
    private TextView sign;
    private Button commit;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_user);

        viewModel = new ViewModelProvider(this).get(ModifyUserViewModel.class);
        viewModel.getToastText().observe(this, s -> {
            Toast.makeText(ModifyUserActivity.this, s, Toast.LENGTH_SHORT).show();
        });
        // 修改成功， 返回数据
        viewModel.getState().observe(this, aBoolean -> {
            if(aBoolean){
                if(progressBar != null){
                    progressBar.setVisibility(View.GONE);
                }
                Intent intent = new Intent();
                intent.putExtra("user", viewModel.getUser());
                setResult(ActivityCode.MOD_USER_RESULT_OK, intent);
                finish();
            }
        });

        Intent intent = getIntent();
        int currUserId = intent.getIntExtra("currUserId", 0);
        if(currUserId == 0){
            Toast.makeText(this, "未登录", Toast.LENGTH_SHORT).show();
            finish();
        }
        viewModel.setCurrUserId(currUserId);
        viewModel.getUser().setId(currUserId);

        QMUITopBarLayout topBar = findViewById(R.id.mod_user_bar);
        topBar.setTitle(R.string.mod_title);
        topBar.addLeftBackImageButton().setOnClickListener(view -> {
            finish();
        });

        initData();
    }

    @Override
    public void finish() {
        // 清除头像缓存
        List<File> images = viewModel.getImages();
        if(images != null){
            for(int i = 0; i < images.size(); i++){
                File file = images.get(i);
                if(file.exists() && file.isFile()){
                    file.delete();
                }
            }
        }

        super.finish();
    }

    private void initData(){
        head = findViewById(R.id.mod_user_head_img);
        name = findViewById(R.id.mod_user_name);
        age = findViewById(R.id.mod_user_age);
        gender = findViewById(R.id.mod_user_gender);
        star = findViewById(R.id.mod_user_star);
        city = findViewById(R.id.mod_user_city);
        hobby = findViewById(R.id.mod_user_hobby);
        sign = findViewById(R.id.mod_user_signature);
        commit = findViewById(R.id.mod_user_commit);

        // 头像
        head.setClickable(true);
        head.setOnClickListener(view -> {
            ArrayList<String> images = new ArrayList<>();
            ImageSelector.builder()
                    .useCamera(false) // 设置是否使用拍照
                    .setSingle(false)  //设置是否单选
                    .setMaxSelectCount(1) // 图片的最大选择数量，小于等于0时，不限数量。
                    .setSelected(images) // 把已选的图片传入默认选中。
                    .canPreview(true) //是否可以预览图片，默认为true
                    .start(ModifyUserActivity.this, ActivityCode.LOCAL_IMAGE); // 打开相册
        });
        // 提交
        commit.setOnClickListener(view -> {
            commitInfo();
        });
    }

    /**
     * 提交信息
     */
    private void commitInfo(){
        String chooseGender = null;
        for (int i = 0; i < gender.getChildCount(); i++) {
            RadioButton rd = (RadioButton) gender.getChildAt(i);
            if (rd.isChecked()) {
                chooseGender = rd.getText().toString();
                break;
            }
        }
        viewModel.getUser().setName(name.getText().toString());
        int ageTem = Integer.parseInt(StringUtil.isEmpty(age.getText().toString()) ? "0" : age.getText().toString());
        if(ageTem < 0 ){
            ageTem = 0;
        }
        if(ageTem > 999){
            ageTem = 999;
        }
        viewModel.getUser().setAge(ageTem);
        viewModel.getUser().setGender(chooseGender);
        viewModel.getUser().setStarsign(star.getText().toString());
        viewModel.getUser().setCity(city.getText().toString());
        viewModel.getUser().setHobby(hobby.getText().toString());
        viewModel.getUser().setSignature(sign.getText().toString());

        // 提交
        viewModel.commit();
        progressBar = findViewById(R.id.mod_user_progressBar);
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            // 设置页面获取权限的结果
            case ActivityCode.PERMISSION_CODE :
                if (resultCode == RESULT_OK) {
                    checkPermission();
                }
                break;
            //获取图片选择器返回的数据
            case ActivityCode.LOCAL_IMAGE :
                if(data != null){
                    ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                    displayImages(images);
                }
                break;
        }
    }

    /**
     * 展示选中的图片
     */
    private void displayImages(List<String> images){
        List<File> files = new ArrayList<>();
        // 将图片转换成临时缓存并重命名
        for(int i = 0; i < images.size(); i++){
            Uri uri = UriUtils.getImageContentUri(this, images.get(i));
            Bitmap bitmap = ImageUtil.getBitmapFromUri(this, uri);
            String imageName = UUID.randomUUID() + ".jpg";
            // 创建缓存文件
            File imageFile = new File(getExternalCacheDir().getPath() + File.separator + imageName);
            try {
                // 写入文件
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imageFile));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                ThrowException.print(e, "图片转化失败");
                return;
            }
            files.add(imageFile);
            head.setImageURI(UriUtils.getImageContentUri(this, imageFile.getPath()));
            viewModel.getUser().setHeadimg(imageName);
        }
        viewModel.setImage(files);
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }
    /**
     * 权限申请结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == ActivityCode.PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                // 没有权限，主动跳转到权限设置页面
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }
}